package com.dlc.felear.xiaoensale.helper;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.TypeReference;
import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.dao.CookingMenuDao;
import com.dlc.felear.xiaoensale.dao.MenuFoodMaterialDao;
import com.dlc.felear.xiaoensale.dao.OperatorDao;
import com.dlc.felear.xiaoensale.entity.CookingMenu;
import com.dlc.felear.xiaoensale.entity.FoodMaterialList;
import com.dlc.felear.xiaoensale.entity.MenuFoodMaterial;
import com.dlc.felear.xiaoensale.entity.Operator;
import com.dlc.felear.xiaoensale.entity.OrgMenuListData;
import com.dlc.felear.xiaoensale.utils.HttpApi;
import com.dlc.felear.xiaoensale.utils.JasyptUtil;
import com.dlc.felear.xiaoensale.utils.MenuPicUtil;
import com.dlc.felear.xiaoensale.utils.TimeUtils;
import com.itdlc.android.library.utils.APPDidUtil;
import com.itdlc.android.library.utils.NetStateUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.commons.lang3.StringEscapeUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.Call;

public class LoadDataHelper {
    private static final String TAG = "LoadDataHelper";
    private Context context;
    private ExecutorService executorService;
    private MenuFoodMaterialDao menuFoodMaterialDao;
    private CookingMenuDao cookingMenuDao;
    private OperatorDao operatorDao;
    private static LoadDataHelper instance;
    private int function;
    private CookingMenuMangerHelper cookingMenuMangerHelper;
    private String deviceType = "M400";
    private String deviceId=APPDidUtil.getAppDid();

    public void setDisableDialog(boolean disableDialog) {

    }

    public static LoadDataHelper getInstance(Context context) {
        if (instance == null) {
            synchronized (LoadDataHelper.class) {
                if (instance == null) {
                    instance = new LoadDataHelper(context);
                }
            }
        }
        return instance;
    }

    private LoadDataHelper(Context context) {
        this.context = context;
        deviceType = Session.getSession().getString(Constant.D_GT_TYPE, "M600");
        executorService = Executors.newFixedThreadPool(2);
        menuFoodMaterialDao = new MenuFoodMaterialDao(context);
        cookingMenuDao = new CookingMenuDao(context);
        operatorDao = new OperatorDao(context);
        function = Session.getSession().getInt(Constant.DEVICE_FUNTION, 0);
        cookingMenuMangerHelper = CookingMenuMangerHelper.getInstance(context, cookingMenuDao);
        Log.e(TAG, "function:" + function);
    }

    public void initDtatByOsstart() {
        try {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (function == 1) {
                            loadFoodMaterialData();
                        } else if (function == 2) {
                            if (NetStateUtils.isNetworkConnected(context)) {
                                cookingMenuDao.deleteAll();
                                Thread.sleep(4000);
                            }
                            loadOrgMenuList(1, true);
                        } else {
                            if (NetStateUtils.isNetworkConnected(context)) {
//                                cookingMenuDao.deleteAll();
                            }
                            Thread.sleep(4000);
                            loadOrgMenuList(1, true);
                            loadFoodMaterialData();
                        }
                    } catch (Exception e) {
                        Log.e(TAG, e.getMessage());
                    }
                }
            });
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    /**
     * 删除没有炒步骤的菜谱
     */



    public void loadFoodMaterialData() {
        HashMap<String, Object> paramers = new HashMap<>();
        paramers.put("deviceId", APPDidUtil.getAppDid());
        String sign = JasyptUtil.getInstance().getSign(paramers);
        paramers.put("sign", sign);
        showDialog();
        OkHttpManager.HttpPostJson(HttpApi.URL_FOODLIST, paramers, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                Log.e(TAG, "食材数据" + e.getMessage());
                closeDialog();
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    Log.e(TAG, "食材数据" + s);
                    closeDialog();
                    FoodMaterialList list = JsonHelper.parserJson(s, FoodMaterialList.class);
                    if (list != null && list.getCode() == 1) {
                        saveFoodMatrial(list.getData());
                    }
                } catch (Exception e) {

                }

            }
        });
    }


    public void loadOrgMenuList(int pageNum, final boolean loop) {
        HashMap<String, Object> paramers = new HashMap<>();
        paramers.put("deviceId", APPDidUtil.getAppDid());
        paramers.put("pageSize", 20);
        paramers.put("pageNum", pageNum);
        String sign = JasyptUtil.getInstance().getSign(paramers);
        paramers.put("sign", sign);
        Log.e(TAG, "loadOrgMenuList 请求参数" + JsonHelper.toJson(paramers) + " loop:" + loop);
        showDialog();
        OkHttpManager.HttpPostJson(HttpApi.URL_GETORGFOODMENULIST, paramers, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                Log.e(TAG, "运营商菜谱数据" + e.getMessage());
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    Log.e(TAG, "运营商菜谱数据" + s);
                    OrgMenuListData orgMenuListData = JsonHelper.parserJson(s, OrgMenuListData.class);
                    Log.e(TAG, "运营商菜谱数据 orgMenuListData" + JsonHelper.toJson(orgMenuListData));
                    if (orgMenuListData != null && orgMenuListData.getCode() == 1 && orgMenuListData.getData() != null) {
                        handleOrgMenuData(orgMenuListData.getData(), Constant.MENU_NORMAL);
                        if (loop) {
                            fenyeJiazai(orgMenuListData.getData(), Constant.MENU_NORMAL);
                        }
                    }
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage());
                }

            }
        });
    }

    private void fenyeJiazai(OrgMenuListData.DataSize dataSize, int type) {
        if (dataSize.getPageSize() > dataSize.getSize()) {
            Log.e(TAG, "不需要分页");
            return;
        }
        int totalPages = (int) Math.ceil((float) dataSize.getTotal() / (float) dataSize.getPageSize());
        if (dataSize.getPageNum() < totalPages) {
            Log.e(TAG, "分页加载:" + (dataSize.getPageNum() + 1));
            loadOrgMenuList(dataSize.getPageNum() + 1, true);
        } else {
            Log.e(TAG, "不满足分页要求:");
        }
    }


    private void handleOrgMenuData(final OrgMenuListData.DataSize data, final int level) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    if (data.getList() != null) {
//                        Log.e(TAG, "getList=" + data.getList().size());
                        for (OrgMenuListData.DataSize.ListMenu menu : data.getList()) {
                            if (!TextUtils.isEmpty(menu.getPic()) && menu.getPicFileLength() > 0) {
                                downPic(menu.getFoodmenuName(), menu.getPic(), menu.getPicFileLength());
                            }
                            if(TextUtils.equals(menu.getFoodmenuName(),"干豆角蒸肉HZ")){
                                Log.e(TAG, "getFoodmenuName name:" + menu.getFoodmenuName() +JsonHelper.toJson(menu));
                            }
                            if (function == 0 && !TextUtils.equals(menu.getMachineModoel(), deviceType)) {
                                Log.e(TAG, "机器型号不符:" + menu.getFoodmenuName() + " MachineModoel:" + menu.getMachineModoel());
                                continue;
                            }
                            String id = menu.getId() + "_" + menu.getMachineModoel() + Integer.toString(menu.getWeight() / 1000);
                            Log.e(TAG, "菜谱:" + menu.getFoodmenuName() + " id:" + menu.getId() + " machineModoel:" + menu.getMachineModoel());
                            if (menu.getMachineModoel() == null || TextUtils.isEmpty(menu.getMachineModoel())) {
                                Log.e(TAG, "其他菜谱111:" + menu.getFoodmenuName() + " id:" + menu.getId());
                                id = menu.getId();
                            }
                            CookingMenu cookingMenu = cookingMenuDao.queryById(id);
                            if (cookingMenu == null ||
                                    (cookingMenu.getType() == 0 && cookingMenu.getType() != menu.getIsdelete())) {
                                if (cookingMenu == null) {
                                    Log.e(TAG, "数据库不存在菜谱:" + menu.getFoodmenuName() + " id:" + menu.getId() + " id1:" + id);
                                    cookingMenu = new CookingMenu();
                                }
                                cookingMenu.setId(id);
                                threadSave(cookingMenu, menu);
                            } else if (!TextUtils.isEmpty(menu.getPic()) && TextUtils.isEmpty(cookingMenu.getPic())) {
                                //更新图片
                                Log.e(TAG,"更新图片:"+menu.getFoodmenuName());
                                cookingMenu.setPic(menu.getPic());
                                cookingMenuDao.createOrUpdate(cookingMenu);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e(TAG, "handleOrgMenuData Exception:" + e.getMessage());
                }
            }
        });
    }

    private void threadSave(final CookingMenu cookingMenu, final OrgMenuListData.DataSize.ListMenu menu) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                cookingMenu.setCreateTime(TimeUtils.getTimeYMDHMS(menu.getEtime()));
                cookingMenu.setUpdateTime(TimeUtils.getTimeYMDHMS(menu.getEtime()));
                cookingMenu.setId(menu.getId());
                cookingMenu.setPic(menu.getPic());
                cookingMenu.setMachineModoel(menu.getMachineModoel());
                cookingMenu.setName(menu.getFoodmenuName());
                cookingMenu.setLevel(menu.getMachineModoel());
                cookingMenu.setCookingType(menu.getCookingType());
                cookingMenu.setParam1(menu.getParam1());
                cookingMenu.setParam2(menu.getParam2());
                cookingMenu.setParam3(menu.getParam3());
                cookingMenu.setParam4(menu.getParam4());
                cookingMenu.setDesc(menu.getVdesc());
                int type = menu.getIsdelete() == 0 ? Constant.MENU_NORMAL : Constant.MENU_STD;
                cookingMenu.setType(type);
                cookingMenu.setUploaded(1);
                cookingMenu.setSpecification(Integer.toString(menu.getWeight() / 1000));
                saveOrgMenuData(cookingMenu, menu);
            }
        });

    }


    private void test(CookingMenu cookingMenu, OrgMenuListData.DataSize.ListMenu menu) {
//        menu.setProportionList(null);
//        menu.setStepJson("");
//        if (TextUtils.equals(menu.getFoodmenuName(), "黄豆焖鸭DY") && cookingMenu != null) {
//            Log.e(TAG, "test menu=" + menu.getIsdelete() + " " + cookingMenu.getType());
//        }
//
    }

    /**
     * 更新菜谱数据
     *
     * @param cookingMenu
     * @param menu
     */
    private void saveOrgMenuData(CookingMenu cookingMenu, OrgMenuListData.DataSize.ListMenu menu) {
        //function 0炒菜机 1毛菜入库 2配菜台
        try {
            if (TextUtils.isEmpty(menu.getParam1()) && (TextUtils.equals(menu.getMachineModoel(), "M400")
                    || TextUtils.equals(menu.getMachineModoel(), "M600") || TextUtils.equals(menu.getMachineModoel(), "M260"))) {
                Log.e(TAG, "没有炒菜公式 menuName:" + menu.getFoodmenuName() + " Param1:" + menu.getParam1());
                return;
            }
            if (function == 2) {
                if (TextUtils.isEmpty(menu.getStepJson()) ||
                        TextUtils.isEmpty(menu.getMachineModoel())) {
                    cookingMenu.setMachineModoel(Constant.ZHENGCAI);
                    Log.e(TAG, "其他菜谱 menuName:" + menu.getFoodmenuName() + " type:" + menu.getIsdelete());
                }
                cookingMenu.setOperators(null);
                cookingMenu.setFoodMaterials(saveMenuFoodmaterial(Constant.FOODS_TYPE_2, cookingMenu.getId(), menu.getProportionList()));
                cookingMenuDao.createOrUpdateAll(cookingMenu);
                cookingMenuMangerHelper.updateCookingMenu(cookingMenu);
                Log.e(TAG, "更新配菜台 menuName:" + menu.getFoodmenuName());
            } else if (function == 0 && !TextUtils.isEmpty(menu.getStepJson())) {
                cookingMenu.setOperators(saveActionStepInfo(menu.getStepJson()));
                cookingMenu.setFoodMaterials(saveMenuFoodmaterial(Constant.FOODS_TYPE_2, cookingMenu.getId(), menu.getProportionList()));
                cookingMenuDao.createOrUpdateAll(cookingMenu);
                cookingMenuMangerHelper.updateCookingMenu(cookingMenu);
            }
        } catch (Exception e) {
            Log.e(TAG, "saveOrgMenuData Exception:" + e.getMessage());
        }
    }


    private void downPic(String name, String pic, long picFileLength) {
        try {
            MenuPicUtil.getInstance(context).addDownLoadPicTask(name, pic, picFileLength);
        } catch (Exception e) {
            Log.e(TAG, "downPic:" + e.getMessage());
        }
    }


    public void deleteEMNU() {
    }

    private List<Operator> saveActionStepInfo(String stepJson) {
        List<Operator> list = null;
        try {
            list = JsonHelper.parserJson(StringEscapeUtils.unescapeJava(stepJson),
                    new TypeReference<List<Operator>>() {
                    });
        } catch (Exception e) {
            Log.e(TAG, "saveActionStepInfo Exception=" + e.getMessage());
        }

        return list;
    }

    private List<MenuFoodMaterial> saveMenuFoodmaterial(int level, String cid, List<OrgMenuListData.DataSize.ListMenu.ProportionList> proportionList) {
        List<MenuFoodMaterial> list = new ArrayList<>();
        menuFoodMaterialDao.deleteForCid(cid);
        if (null != proportionList) {
            for (OrgMenuListData.DataSize.ListMenu.ProportionList proportion : proportionList) {
                MenuFoodMaterial foodMaterial = new MenuFoodMaterial();
                foodMaterial.setCid(cid);
                foodMaterial.setId(proportion.getId());
                foodMaterial.setFoodName(proportion.getFoodName());
                foodMaterial.setFoodid(proportion.getFoodid());
                foodMaterial.setNumber(proportion.getScaleNo());
                foodMaterial.setWeight(proportion.getWeight());
                foodMaterial.setType(level);
//                Log.e(TAG, "saveMenuFoodmaterial: MenuFoodMaterial" + JsonHelper.toJson(foodMaterial));
                list.add(foodMaterial);
            }
        }
        return list;
    }

    private void saveFoodMatrial(final List<MenuFoodMaterial> list) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                for (MenuFoodMaterial menuFoodMaterial : list) {
                    menuFoodMaterial.setType(Constant.FOODS_TYPE_1);
                    menuFoodMaterial.setId(deviceId+menuFoodMaterial.getFoodid());
                    menuFoodMaterialDao.addOrUpdateStd(menuFoodMaterial);
                }
                delete(list);
            }
        });
    }

    /**
     * 删除云数据库已删除的食材
     *
     * @param list
     */
    private void delete(List<MenuFoodMaterial> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        List<MenuFoodMaterial> tempList = menuFoodMaterialDao.queryForAll((Constant.FOODS_TYPE_1));
        if (tempList == null || tempList.isEmpty()) {
            return;
        }
//        Log.e(TAG, "list=" + list.size() + " tempList=" + tempList.size());
        Map<Integer, MenuFoodMaterial> tempMap = new HashMap<>();
        for (MenuFoodMaterial f : list) {
            tempMap.put(f.getFoodid(), f);
        }

        for (MenuFoodMaterial f : tempList) {
            if (!tempMap.containsKey(f.getFoodid())) {
//                Log.e(TAG, "删除：" + JsonHelper.toJson(f));
                menuFoodMaterialDao.delete(f);
            }
        }
//        Log.e(TAG, "删除后 size=" + menuFoodMaterialDao.queryForAll((Constant.FOODS_TYPE_1)).size());
    }


    private void showDialog() {
//        if(!disableDialog){
//           return;
//        }
//        if(loadingDialog==null){
//            loadingDialog=new LoadingDialog(context,"正在执行...");
//        }
//        if(loadingDialog!=null){
//            loadingDialog.show();
//        }
    }

    private void closeDialog() {
//        if(!disableDialog){
//            return;
//        }
//        if(loadingDialog!=null){
//            loadingDialog.close();
//        }
    }
}
